package edu.bbu.license.client.android.controller.settings;

import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioGroup;
import edu.bbu.license.client.android.R;
import edu.bbu.license.client.android.controller.BaseController;
import edu.bbu.license.client.android.gui.settings.SettingsView;
import edu.bbu.license.client.android.services.BaseService;

public class SettingsController extends BaseController {

	private volatile SettingsView settingsView;
	private static SettingsController controllerInstance = null;
	
	public static synchronized SettingsController getInstance() {
		if(controllerInstance == null) {
			controllerInstance = new SettingsController();
		}
		
		return controllerInstance;
	}
	
	public synchronized void atach(SettingsView settingsView) {
		if(settingsView != null) {
			this.settingsView = settingsView;
			initializeFilesView();
		}
	}
	
	private void initializeFilesView() {
		settingsView.setAutoSyncEnable(((BaseService) getFileService()).isAutoSyncEnabled());
		settingsView.setAutoSyncChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				((BaseService) getFileService()).setAutoSyncEnabled(isChecked);
			}
		});
		
		if(((BaseService) getFileService()).isOneWaySyncTypeSet()) {
			settingsView.setOneWaySyncTypeChecked();
		} else {
			settingsView.setTwoWaySyncTypeChecked();
		}
		
		settingsView.setSyncTyepeChangeListener(new RadioGroup.OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if(checkedId == R.id.settings_activity_one_way_sync) {
					((BaseService) getFileService()).setOneWaySyncType();
				} else {
					((BaseService) getFileService()).setTwoWaySyncType();
				}
			}
		});
		
		settingsView.setLocalSyncFolder(((BaseService) getFileService()).getLocalSyncDirectory());
		settingsView.setServerSyncFolder("/base/sync");
	}
}
